/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.wsinfra.wse.impl;

import java.util.Calendar;

import javax.xml.namespace.QName;

import org.apache.xmlbeans.XmlDateTime;

import cgl.narada.wsinfra.exception.WsFaultException;
import cgl.narada.wsinfra.schemas.addressing.ActionDocument;
import cgl.narada.wsinfra.schemas.addressing.EndpointReferenceType;
import cgl.narada.wsinfra.schemas.addressing.FromDocument;
import cgl.narada.wsinfra.schemas.addressing.RelatesToDocument;
import cgl.narada.wsinfra.schemas.eventing.DeliveryType;
import cgl.narada.wsinfra.schemas.eventing.FilterType;
import cgl.narada.wsinfra.schemas.eventing.SubscribeDocument;
import cgl.narada.wsinfra.schemas.eventing.SubscribeResponseDocument;
import cgl.narada.wsinfra.schemas.soap.EnvelopeDocument;
import cgl.narada.wsinfra.util.QNameLocator;
import cgl.narada.wsinfra.util.SoapMessageAlteration;
import cgl.narada.wsinfra.util.UUIDRetrieval;
import cgl.narada.wsinfra.wsa.AddressingHeaders;
import cgl.narada.wsinfra.wsa.WsaEnvelopeCreator;
import cgl.narada.wsinfra.wsa.WsaEprCreator;
import cgl.narada.wsinfra.wsa.WsaProcessingFactory;
import cgl.narada.wsinfra.wse.WseActions;
import cgl.narada.wsinfra.wse.WseFaults;
import cgl.narada.wsinfra.wse.WseNodeUtils;
import cgl.narada.wsinfra.wse.WseProcessingFactory;
import cgl.narada.wsinfra.wse.WseQNames;
import cgl.narada.wsinfra.wse.matching.SubscriptionEntry;
import cgl.narada.wsinfra.wse.matching.SubscriptionEntryFactory;
import cgl.narada.wsinfra.wse.matching.SubscriptionManagement;
import cgl.narada.wsinfra.wse.matching.SubscriptionPolicies;
import cgl.narada.wsinfra.wse.matching.SubscriptionValidator;

/** Class which implements functionality related to processing subscription
    requests received at a source.

    @author Shrideep Pallickara
    $Date: 2005/07/29 22:41:30 $
    $Revision: 1.6 $
*/


public class SourceSubscribeRequestProcessing {

  public static final SourceSubscribeRequestProcessing instance =
  new SourceSubscribeRequestProcessing();

  private SubscriptionEntryFactory subscriptionEntryFactory;
  private SubscriptionValidator subscriptionValidator;
  private SubscriptionPolicies subscriptionPolicies;

  private QNameLocator qNameLocator;

  private WseQNames wseQNames;
  private WseActions wseActions;
  private WseFaults wseFaults;
  private WseNodeUtils wseNodeUtils;

  private UUIDRetrieval retriever;

  private WsaEprCreator wsaEprCreator;
  private WsaEnvelopeCreator wsaEnvelopeCreator;

  private SoapMessageAlteration soapMessageAlteration;
  private String moduleName = "SourceSubscribeRequestProcessing: ";


  private SourceSubscribeRequestProcessing() {
    subscriptionEntryFactory = SubscriptionEntryFactory.getInstance();
    subscriptionValidator = SubscriptionValidator.getInstance();
    subscriptionPolicies =  SubscriptionPolicies.getInstance();

    wseQNames = WseQNames.getInstance();
    wseActions = WseActions.getInstance();
    wseNodeUtils = WseProcessingFactory.getWseNodeUtils();

    qNameLocator = QNameLocator.getInstance();
    retriever = UUIDRetrieval.getInstance();
    soapMessageAlteration = SoapMessageAlteration.getInstance();

    wsaEprCreator = WsaProcessingFactory.getWsaEprCreator();
    wsaEnvelopeCreator = WsaProcessingFactory.getWsaEnvelopeCreator();
  }



  public static SourceSubscribeRequestProcessing getInstance() {
    return instance;
  }


  /** The method to process a SubscriptionRequest issued by a Sink. If this
      request is successfully processed a SubscriptionEntry object is 
      returned. If the request is NOT successful a WsFaultException is thrown.
  */
  public SubscriptionEntry 
  processSubscribeRequest(SubscribeDocument subscribeDocument,
			  SubscriptionManagement subscriptionManagement,
			  EndpointReferenceType sourceEpr,
			  EndpointReferenceType subscriptionManagerEpr)
    throws WsFaultException {
   
    subscriptionValidator.validateSubscription(subscribeDocument);

    EndpointReferenceType notifyTo = 
      wseNodeUtils.getNotifyTo(subscribeDocument);
   
    SubscribeDocument.Subscribe subscribe =
      subscribeDocument.getSubscribe();
    Calendar expires = (Calendar) subscribe.getExpires();
    Calendar expiresAt =  subscriptionPolicies.getExpiry(expires);

    FilterType filter = subscribe.getFilter();
    DeliveryType delivery = subscribe.getDelivery();


    /** Processing related to EndTo. If this is PRESENT SubscriptionEnd
	notifications are expected and must be sent to the location specified
	in the endTo. */
    EndpointReferenceType endTo = null;
    boolean hasEndTo = subscribe.isSetEndTo();
    if (hasEndTo) {
      endTo = subscribe.getEndTo();
    }


    String subscriptionUUID = retriever.getRandomBasedUUIDAsString();
    SubscriptionEntry subscribeEntry =
      subscriptionEntryFactory.createEntry(subscriptionUUID, filter, expiresAt,
					   sourceEpr, notifyTo, endTo,
					   subscriptionManagerEpr);

    subscriptionManagement.addEntry(subscribeEntry);

    return subscribeEntry;
    /**SubscribeResponseDocument subscribeResponseDocument =
       createSubscribeResponseDocument(subscribeEntry);
       
       return subscribeResponseDocument; */
  }


  /** This method create a subscribe response document based on the
      newly create subscription entry */
  private SubscribeResponseDocument
  createSubscribeResponseDocument(SubscriptionEntry subscribeEntry) {
    SubscribeResponseDocument subscribeResponseDoc =
      SubscribeResponseDocument.Factory.newInstance();

    SubscribeResponseDocument.SubscribeResponse subscribeResponse
      = subscribeResponseDoc.addNewSubscribeResponse();

    XmlDateTime xmlDateTime = XmlDateTime.Factory.newInstance();
    xmlDateTime.setCalendarValue(subscribeEntry.getExpiresAt() );

    subscribeResponse.setExpires(xmlDateTime);

    EndpointReferenceType subscriptionManager =
      subscribeEntry.getSubscriptionManager();

    /** This is done so that the referenceType of the subscriptionManager is
	not messed up. Otherwise every addition is continously added */
    EndpointReferenceType subscriptionManagerCopy =
      (EndpointReferenceType)subscriptionManager.copy();

    String subscriptionId = subscribeEntry.getIdentifier();
    QName identifierQName = wseQNames.getIdentifier();
    wsaEprCreator.addElementToReferenceParameters(subscriptionManagerCopy,
						  identifierQName,
						  subscriptionId);
    subscribeResponse.setSubscriptionManager(subscriptionManagerCopy);


    return subscribeResponseDoc;
  }



  /** This method creates the appropriate SOAP envelope for the subscription
      response. It takes care to ensure that the appropriate Action headers,
      RelatesTo, MessageId, To and From Headers are appropriately filled. */
  public EnvelopeDocument
  createEnvelopedResponse(AddressingHeaders requestHeaders,
			  SubscribeResponseDocument subscribeResponseDocument){

    EndpointReferenceType to = initializeTo(requestHeaders);
    if (to == null) {
      System.out.println(moduleName +
			 "No destination to Send (To) has been specified");
      return null;
    }


    RelatesToDocument relatesTo = null;
    if (requestHeaders.hasMessageID()) {
      String messageId =
	requestHeaders.getMessageID().getMessageID().getStringValue();
      relatesTo = RelatesToDocument.Factory.newInstance();
      relatesTo.addNewRelatesTo().setStringValue(messageId);
    }

    ActionDocument action = wseActions.getSubscribeResponseAction();
    FromDocument from = null;

    EnvelopeDocument envelopeDocument =
      wsaEnvelopeCreator.createSoapEnvelope(to, from, action, relatesTo);

    soapMessageAlteration.addToSoapBody(envelopeDocument,
					subscribeResponseDocument);
    return envelopeDocument;
  }




   /** This method creates the appropriate SOAP envelope for the subscription
      response. It takes care to ensure that the appropriate Action headers,
      RelatesTo, MessageId, To and From Headers are appropriately filled. */
  public EnvelopeDocument
  createEnvelopeForSubManager(EndpointReferenceType sourceEpr,
			      EndpointReferenceType subscriptionManagerEpr,
			      SubscribeDocument subscribeDocument,
			      SubscribeResponseDocument subResponseDocument){

    EndpointReferenceType to = subscriptionManagerEpr;

    if (to == null) {
      System.out.println(moduleName +
			 "No destination to Send (To) has been specified");
      return null;
    }


    RelatesToDocument relatesTo = null;
    ActionDocument action = wseActions.getSubscribeResponseAction();

    FromDocument from = FromDocument.Factory.newInstance();
    from.setFrom(sourceEpr);

    EnvelopeDocument envelopeDocument =
      wsaEnvelopeCreator.createSoapEnvelope(to, from, action, relatesTo);

    soapMessageAlteration.addToSoapBody(envelopeDocument, subResponseDocument);
    soapMessageAlteration.addToSoapBody(envelopeDocument, subscribeDocument);

    return envelopeDocument;
  }



  /** Computes the destination to send a Message To based on the specified
      Addressing Headers */
  private EndpointReferenceType
  initializeTo(AddressingHeaders requestHeaders) {
    EndpointReferenceType to = null;

    boolean toInitialized=false;
    if (requestHeaders.hasReplyTo()) {
      to = requestHeaders.getReplyTo().getReplyTo();
      toInitialized=true;
    }

    if (!toInitialized) {
      if (requestHeaders.hasFrom()) {
	to = requestHeaders.getFrom().getFrom();
	toInitialized=true;
      }
    }

    return to;
  }
}


